﻿ 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
 
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
using System.Linq.Expressions;
using System.Data.SqlClient;


namespace WorkBasket.Data.Contracts
    {




        public class RepositoryBase<T> :  IRepository<T> where T : class 
        {
            protected DbContext ThisDbContext { get; set; }
            protected DbSet<T> ThisDBset { get; set; }
     

            public RepositoryBase(DbContext context)
            {
                //if (ThisDbContext == null)
                //    throw new ArgumentNullException("dbcontext");
                ThisDbContext = context;
                ThisDBset = ThisDbContext.Set<T>();
            }
 
   


            public IQueryable<T> GetAll()
            {
                return ThisDBset ;
 
            }
         
 
            public T GetByID(int ID)
            {
                return ThisDBset.Find(ID);
            }
            public T GetByID(string ID)
            {
                return ThisDBset.Find(ID);
            }

            public IQueryable<T> Where(Expression<Func<T, bool>> predicate) 
            {

                return ThisDBset.Where<T>(predicate).AsQueryable<T>();
                
            }
 

            public void Add(T entity)
            {
                DbEntityEntry dbEntEntry = ThisDbContext.Entry(entity);
                if (dbEntEntry.State != EntityState.Deleted)
                {
                    dbEntEntry.State = EntityState.Added;
                }
                else
                {
                    ThisDBset.Add(entity);

                }


            }

            public void Update(T Entity)
            {
                DbEntityEntry dbEntEntry = ThisDbContext.Entry(Entity);
                if (dbEntEntry.State == EntityState.Deleted)
                {
                    ThisDBset.Attach(Entity);
                }
                dbEntEntry.State = EntityState.Modified;
            }

            public void Delete(T Entity)
            {
                ThisDBset.Remove(Entity);
            }

            public void Delete(int ID)
            {
             ThisDBset.Remove(ThisDBset.Find(ID));
            }

           


        }
    }
 
